var stripe = Stripe('pk_live_sj05FFLZO3pML3O9I5sapRlw00CvWUqCCg');
var stripeButton = document.getElementById('checkout-button');
var output = document.getElementById('donate-val');
var paypal_val = document.getElementById('paypal-single-val');
var paypal_sub_val = document.getElementById('paypal-sub-val');
var giftShirtLock = document.querySelector(".loveKiCadLocked");
var giftShirtUnlock = document.querySelector(".loveKiCadUnlocked");
var giftShirtBtns = document.querySelector(".giftShirtBtn");
var wantsShirt = 'no';
var shirtSize = 'Med';
var total_output = 0;
var currency_sym = '$';
var default_item = "Support KiCad Development";

var origin = new URL(document.URL);
var loc = origin.searchParams.get('location');

var val_vector = {
    'usd': [15, 30, 50, 120, 250],
    'eur': [15, 30, 50, 120, 250],
    'cny': [60, 150, 300, 900, 1200],
    'jpy': [1500, 4000, 9000, 18000, 25000],
    'gbp': [10, 20, 40, 95, 150],
    'inr': [800, 2000, 4000, 10000, 15000]
};

// These values ensure that not more than 10% of the donation goes to processing fees
var min_vector = {
    'usd': 8,
    'eur': 6,
    'cny': 35,
    'jpy': 750,
    'gbp': 4,
    'inr': 425
};

var currency = 'usd';

if (loc != null) {
    document.getElementById('paypal-single-cancel').value = 'https://www.kicad.org/' + loc;
    document.getElementById('paypal-sub-cancel').value = 'https://www.kicad.org/' + loc;
}

// Initialize subscription buttons
if (document.getElementById('cb_freq_single').checked) {
    document.getElementById('paypal-single').style = "display: inline;"
    document.getElementById('paypal-sub').style = "display: none;"
    document.getElementById('checkout-button').disabled = false;
} else {
    document.getElementById('paypal-single').style = "display: none;"
    document.getElementById('paypal-sub').style = "display: inline;"
    document.getElementById('paypal-sub-len').value = "1"
    document.getElementById('checkout-button').disabled = true;
}

function updateDonationAmount(amount) {
    output.value = amount;
    updateOutputNumbers(false);

}

// Add click event listener to the donation options
const donationOptions = document.getElementById('donation-options');
donationOptions.addEventListener('click', function (event) {
    // Check if the clicked element is an <li> inside the donation options
    if (event.target.tagName === 'LI') {
        // Get the text content of the clicked <li> and convert it to a numeric value
        const clickedAmount = parseFloat(event.target.textContent.trim().replace(/[^\d.]/g, ''));
        // Update the donation amount
        updateDonationAmount(clickedAmount);
    }
});

output.addEventListener('input', function() {
    updateOutputNumbers(false);
});

function updateVals() {
    currency = document.querySelector('#currency').textContent.toLowerCase();

    if (currency == 'cny') {
        document.getElementById('paypal-sub-btn').disabled = true;
        document.getElementById('paypal-single-btn').disabled = true;
        document.getElementById('checkout-button').textContent = 'Donate via AliPay'
    } else if (currency == 'inr') {
        document.getElementById('checkout-button').textContent = 'Donate via Credit Card/eWallet'
        document.getElementById('paypal-single-btn').disabled = true;
        document.getElementById('paypal-sub-btn').disabled = true;
    } else {
        document.getElementById('checkout-button').textContent = 'Donate via Credit Card/eWallet'
        document.getElementById('paypal-single-btn').disabled = false;
        document.getElementById('paypal-sub-btn').disabled = false;
    }


    if (currency == 'eur') {
        currency_sym = '€';
    } else if (currency == 'cny') {
        currency_sym = '¥';
    } else if (currency == 'jpy') {
        currency_sym = '¥';
    } else if (currency == 'gbp') {
        currency_sym = '₤';
    } else if (currency == 'inr') {
        currency_sym = '₹';
    }else if (currency == 'usd') {
        currency_sym = '$';
    }

    document.getElementById('paypal-sub-currency').value = currency.toUpperCase();
    document.getElementById('paypal-single-currency').value = currency.toUpperCase();

    document.querySelector('.one').textContent = currency_sym + val_vector[currency][0];
    document.querySelector('.two').textContent = currency_sym + val_vector[currency][1];
    document.querySelector('.three').textContent = currency_sym + val_vector[currency][2];
    document.querySelector('.four').textContent = currency_sym + val_vector[currency][3];
    document.querySelector('.five').textContent = currency_sym + val_vector[currency][4];

    output.min = min_vector[currency];
}
function isMobileView() {
    return window.innerWidth < 600;
}

function updateOutputNumbers(updateOutput) {

    if (updateOutput) {
        output.value = val_vector[currency][2];
    }

    if (!document.getElementById('cb_freq_single').checked || output.value >= val_vector[currency][3]) {
        giftShirtLock.style.display = "none";
        giftShirtUnlock.style.display = "block";
        document.getElementById('tshirt_question').style.display = "block";
        document.getElementById('tshirt_buttons').style.display = "flex";
        document.querySelector(".giftShirtDropdown").disabled = false;
        if (isMobileView()) {
            document.querySelector('.mobile_popup').style = "display: flex;"
        }
    } else {
        giftShirtLock.style.display = "block";
        giftShirtUnlock.style.display = "none";
        document.getElementById('tshirt_question').style.display = "none";
        document.getElementById('tshirt_buttons').style.display = "none";
        document.querySelector(".giftShirtDropdown").disabled = true;
        if (isMobileView()) {
            document.querySelector('.mobile_popup').style = "display: none;"
        }
    }

     let num_val = 0;
     let num_percent = 0.029;
     let num_extra = 0.3;
     let decimals = 2;

    // PayPal and Stripe each charge 1-2% extra for non-USD payments
    // In addition to the currency conversion fee, PayPal also provides
    // a bad exchange rate (about 3% worse) but we try to pay developers
    // in native currencies to avoid this
    if (currency != 'usd') {
        num_percent += 0.02;
    }

    // All transactions add $0.49.  But Euro and GBP are sufficiently close
    // that we don't bother adjusting the offset.  For other currencies, we
    // add an approximate conversion.
    if (currency == 'jpy') {
        num_extra = 41;
        decimals = 0;
    } else if (currency == 'cny') {
        num_extra = 2;
        decimals = 0;
    } else if (currency == 'inr') {
        num_extra = 24;
        decimals = 0;
    }

    num_val = Number(output.value) * (1.0 + num_percent) + num_extra;

    if (document.getElementById('round_up').checked) {
        total_output = num_val.toFixed(decimals);
    } else {
        total_output = Number(output.value).toFixed(decimals);
    }

    paypal_val.value = total_output;
    paypal_sub_val.value = total_output;
    document.getElementById('round_up_sym').textContent = currency_sym;
    document.getElementById('round_up_value').textContent = num_val.toFixed(decimals);
}

stripeButton.addEventListener('click', function() {
    fetch('/create-checkout-session', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                amount: total_output,
                currency: document.querySelector('#currency').textContent,
                backdest: loc,
                tshirt: wantsShirt,
                tshirt_size: shirtSize
            })
        })
        .then(function(response) {
            return response.json();
        })
        .then(function(session) {
            return stripe.redirectToCheckout({
                sessionId: session.id
            });
        })
        .then(function(result) {
            if (result.error) {
                alert(result.error.message);
            }
        })
        .catch(function(error) {
            console.error('Error:', error);
        });
});

(function(jQuery, window, document) {

    $(document).ready(function() {
        updateOutputNumbers(true);

        // Create the popup overlay and content
        var $popupOverlay = $('<div class="popup-overlay"></div>');
        var $popupContent = $('<div class="popup-content"></div>');
        var $popupClose = $('<button class="popup-close">&times;</button>');
        var $popupImage = $('<img src="" alt="Full Size Image" />');

        $popupContent.append($popupClose).append($popupImage);
        $popupOverlay.append($popupContent);
        $('body').append($popupOverlay);
        $popupOverlay.hide();

        // Handle click event on image links
        $('.image-popup').on('click', function(event) {
            event.preventDefault();
            var imageUrl = $(this).attr('data-href');
            $popupImage.attr('src', imageUrl);
            $popupOverlay.show();
        });

        // Handle click event on close button
        $popupClose.on('click', function() {
            $popupOverlay.hide();
        });

        // Handle click event on overlay to close popup
        $popupOverlay.on('click', function(event) {
            if (event.target === this) {
            $popupOverlay.hide();
            }
        });
    })

    $(document).on('click', 'a[class="currency_link"]', function(e) {
        $('#currency')[0].textContent = e.currentTarget.text;
        updateVals();
        updateOutputNumbers(true);
        return false;
    })

    $(document).on('click', 'a[class="size_link"]', function(e) {
        $('#size')[0].textContent = e.currentTarget.text;
        shirtSize = e.currentTarget.text;
        wantsShirt = 'yes';

        if( shirtSize == 'No Shirt' ){
            wantsShirt = 'no';
        }

        if( wantsShirt == 'yes' ){
            document.getElementById('paypal-shirt-size').value = shirtSize;
            document.getElementById('paypal-sub-shirt-size').value = shirtSize;
            document.getElementById('paypal-shipping').value = '2';
            document.getElementById('paypal-sub-shipping').value = '2';
            document.getElementById('paypal-item-name').value = default_item + ' - ' + shirtSize + ' T-Shirt';
            document.getElementById('paypal-sub-item-name').value = default_item + ' - ' + shirtSize + ' T-Shirt';
            var imagePopupDivs = document.querySelectorAll('.image-popup');
            imagePopupDivs.forEach(function(div) {
                if (shirtSize.includes("Fitted")) {
                    div.setAttribute('data-href', '/static/full_shirt_women_fitted_2025.jpg');
                } else if (shirtSize.includes("Women\'s")) {
                    div.setAttribute('data-href', '/static/full_shirt_women_relax_2025.jpg');
                } else {
                    div.setAttribute('data-href', '/static/full_shirt_men_2025.jpg');
                }
            });
        }
        else
        {
            document.getElementById('paypal-shirt-size').value = '';
            document.getElementById('paypal-sub-shirt-size').value = '';
            document.getElementById('paypal-shipping').value = '1';
            document.getElementById('paypal-sub-shipping').value = '1';
            document.getElementById('paypal-item-name').value = default_item;
            document.getElementById('paypal-sub-item-name').value = default_item;
        }

        return false;
    })

    $(document).on('click', 'a[class="round_up"]', function (e) {
        updateOutputNumbers(false);
    })

    $('#cb_freq_single').on('click', function() {
        document.getElementById('paypal-single').style = "display: inline;"
        document.getElementById('paypal-sub').style = "display: none;"
        document.getElementById('checkout-button').disabled = false;
        updateOutputNumbers(false);
    })

    $('#cb_freq_monthly').on('click', function() {
        document.getElementById('paypal-single').style = "display: none;"
        document.getElementById('paypal-sub').style = "display: inline;"
        document.getElementById('paypal-sub-len').value = "1"
        document.getElementById('checkout-button').disabled = true;
        updateOutputNumbers(false);
    })

    $('.popup_close').on('click', function() {
        document.querySelector('.mobile_popup').style = "display: none;"
    })

    $('input.donate-amount').focusout(function() {
        if ($(this).val() < min_vector[currency]) {
            $(this).val(min_vector[currency]);
            updateOutputNumbers(false);
        }
    });

})(jQuery, window, document);